package com.huo.filestransport.service;

import java.util.Date;
import java.util.List;

import com.huo.common.enumtype.FtpFileStatusEnum;
import com.huo.common.enumtype.R;
import com.huo.filestransport.dao.FtpFileInfoDao;
import com.huo.filestransport.dao.FtpfilelogDao;
import com.huo.filestransport.entity.FtpFileInfoEntity;
import com.huo.filestransport.entity.Ftpfilelog;
import com.huo.util.FtpUtil;
import com.huo.util.SpringContextUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TransportThreadService implements Runnable{
	
	private final static Logger logger = LoggerFactory.getLogger(FtpService.class);
	
	private List<FtpFileInfoEntity> ftpFileInfoEntityList;
	
	private String localPath;
	
	private FtpUtil ftpUtil = SpringContextUtil.getBean(FtpUtil.class);
	
	private FtpFileInfoDao ftpFileInfoDao = SpringContextUtil.getBean(FtpFileInfoDao.class);
	
	private FtpfilelogDao ftpfilelogDao = SpringContextUtil.getBean(FtpfilelogDao.class);

	public void setFtpFileInfoEntityList(List<FtpFileInfoEntity> ftpFileInfoEntityList) {
		this.ftpFileInfoEntityList = ftpFileInfoEntityList;
	}

	public void setLocalPath(String localPath) {
		this.localPath = localPath;
	}

	@Override
	public void run() {
		FTPClient ftp = null;
		try {
			ftp = ftpUtil.getFTPConnection();
			for(FtpFileInfoEntity ffie : ftpFileInfoEntityList) {
				Date beginTime = new Date();
				R r = ftpUtil.downloadFtpFileByFtpPath(ffie.getFtpfilepath(),localPath,ftp);
				if("0".equals(String.valueOf(r.get("code")))) {
					//修改记录，将状态改为2
					FtpFileInfoEntity record = new FtpFileInfoEntity();
					record.setId(ffie.getId());
					record.setUpdatetime(new Date());
					record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_FISH.getCode());
					ftpFileInfoDao.updateByPrimaryKeySelective(record);
					//记录日志
					Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
					ftpfilelogRecord.setBegintime(beginTime);
					ftpfilelogRecord.setEndtime(new Date());
					ftpfilelogRecord.setFtpfiledatetime(ffie.getFtpfiledatetime());
					ftpfilelogRecord.setFtpfilename(ffie.getFtpfilename());
					ftpfilelogRecord.setFtpfilepath(ffie.getFtpfilepath());
					ftpfilelogRecord.setFtpfilesize(ffie.getFtpfilesize());
					ftpfilelogRecord.setFtplocalpath(localPath + ffie.getFtpfilepath());
					ftpfilelogDao.insert(ftpfilelogRecord);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);	
		}finally {
			ftpUtil.closeFTPConnection(ftp);
		}
		
	}

}
